//
//  TopicsDetailViewController.m
//  UGoods
//
//  Created by dllo on 16/1/19.
//  Copyright © 2016年 蓝鸥科技.李贺. All rights reserved.
//

#import "TopicsDetailViewController.h"
#import "FindModel.h"
#import "LHAFNetworkTool.h"
#import "BaseCollectionView.h"
#import "BaseCollectionViewFlowLayout.h"
#import "GoodsCollectionViewCell.h"
#import <MJRefresh.h>
#import "TopicsCollectionReusableView.h"
#import <UIImageView+WebCache.h>
#import <MBProgressHUD.h>
#import "BuyDetailViewController.h"
#import "ConstantsDefine.h"
@interface TopicsDetailViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, retain) BaseCollectionView *collectionView;
@property (nonatomic, retain) NSMutableArray *dataArray;
@property (nonatomic, copy) NSString *urlStr;
@property (nonatomic, retain) MBProgressHUD *HUD;

@end

@implementation TopicsDetailViewController

- (void)dealloc
{
    [_collectionView release];
    [_dataArray release];
    [_urlStr release];
    [_HUD release];
    [super dealloc];
}

- (void)handleData {
    NSString *str = [NSString stringWithFormat:@"http://api.ujipin.com/iphone/v1/mobile/index.php?channel=appstore&idfa=1EF25F55-6367-4567-B0D5-82DF4F1557CD&user_id=470825&plantform=iphone&version=314&c=index&a=index&type=1&IOS=1&id=%@", _model.myID];
    self.navigationItem.title = _model.descript;
    [LHAFNetworkTool getUrl:str body:nil response:LHJSON requestHeadFile:nil success:^(NSURLSessionDataTask *task, id resposeObject) {

        NSArray *array = resposeObject[@"result"][@"list"][@"list"];
        self.dataArray = [FindModel modelHandleWithArray:array];
        self.urlStr = [NSString stringWithFormat:@"%@", resposeObject[@"result"][@"list"][@"img_url"]];
        [self.collectionView reloadData];
        [self.collectionView.mj_header endRefreshing];
        [self.HUD hide:YES];
       
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"解析失败：%@", error);
    }];
}

// 下拉刷新
- (void)addHeaderRefresh {
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
        [self.dataArray removeAllObjects];
        [self handleData];
    }];
    // 设置普通状态的动画图片
    NSArray *idleImages = @[[UIImage imageNamed:@"loading_0"]];
    [header setImages:idleImages forState:MJRefreshStateIdle];
    // 设置即将刷新状态的动画图片（一松开就会刷新的状态
    NSArray *pullingImages = @[[UIImage imageNamed:@"loading_0"]];
    [header setImages:pullingImages forState:MJRefreshStatePulling];
    // 设置正在刷新状态的动画图片
    NSMutableArray *refreshingImages = [NSMutableArray array];
    for (NSInteger i = 0; i < 24; i++) {
        [refreshingImages addObject:[UIImage imageNamed:[NSString stringWithFormat:@"loading_%ld", i]]];
    }
    [header setImages:refreshingImages forState:MJRefreshStateRefreshing];
    // 设置所有数据加载完毕的动画图片
    NSArray *NoMoreDataImages = @[[UIImage imageNamed:@"loading_0"]];
    [header setImages:NoMoreDataImages forState:MJRefreshStateNoMoreData];
    
    self.collectionView.mj_header = header;
    
    // 隐藏时间
    header.lastUpdatedTimeLabel.hidden = YES;
    
    // 隐藏状态
    header.stateLabel.hidden = YES;
    
    [self.collectionView.mj_header beginRefreshing];
}

- (void)handleHUD {
    // 1. 创建对象
    self.HUD = [[MBProgressHUD alloc] initWithView:self.view];
    // 2. 添加到当前视图中
    [self.view addSubview:self.HUD];
    // 如果设置此属性, 则置后当前的View
    self.HUD.dimBackground = NO;
    // 设置模式
    self.HUD.mode = MBProgressHUDModeIndeterminate;
    self.HUD.color = [UIColor colorWithWhite:0.800 alpha:1.000];
    [self.HUD show:YES];
}

// 创建collectionView
- (void)createCollectionView {
    BaseCollectionViewFlowLayout *layout = [[BaseCollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake((self.view.frame.size.width - 30 * WIDTH) / 2, 250 * HEIGHT);
    layout.minimumInteritemSpacing = 10 * WIDTH;
    layout.minimumLineSpacing = 10 * HEIGHT;
    layout.sectionInset = UIEdgeInsetsMake(0, 10 * WIDTH, 10 * HEIGHT, 10 * WIDTH);
    layout.headerReferenceSize = CGSizeMake(0, 280 * HEIGHT);
    
    self.collectionView = [[BaseCollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
//    _collectionView.backgroundColor = [UIColor clearColor];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [self.view addSubview:_collectionView];
    [_collectionView release];
    [layout release];
    [_collectionView registerClass:[GoodsCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    //_collectionView的头部
    [_collectionView registerClass:[TopicsCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"top"];
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    TopicsCollectionReusableView *top = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"top" forIndexPath:indexPath];
    
    [top.TopImageView sd_setImageWithURL:[NSURL URLWithString:self.urlStr] placeholderImage:[UIImage imageNamed:@"place"]];
    return top;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    GoodsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    FindModel *model = self.dataArray[indexPath.item];
    cell.model = model;
    return cell;
}

// 点击事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    FindModel *model = self.dataArray[indexPath.item];
    BuyDetailViewController *buy = [[BuyDetailViewController alloc] init];
    buy.model = model;
    [self.navigationController pushViewController:buy animated:YES];
    [buy release];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [self handleData];
    [self createCollectionView];
    [self addHeaderRefresh];
    [self handleHUD];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
